package com.lw.leetcode.binary.b;

/**
 * Created with IntelliJ IDEA.
 * binay
 * 1573. 分割字符串的方案数
 *
 * @author liw
 * @version 1.0
 * @date 2022/1/9 16:34
 */
public class NumWays {

    public static void main(String[] args) {
        NumWays test = new NumWays();

        String str = "111";
        int i = test.numWays(str);
        System.out.println(i);
    }

    public int numWays(String s) {
        int length = s.length();
        int[] arr = new int[length];
        int item = 0;
        for (int i = 0; i < length; i++) {
            if (s.charAt(i) == '1') {
                item++;
            }
            arr[i] = item;
        }
        if (item % 3 != 0) {
            return 0;
        }
        if (item == length) {
            return 1;
        }
        if (item == 0) {
            return (int) ((((long) (length - 2) * (length - 1)) >> 1) % 1000000007);
        } else {
            long a = binary3(arr, item / 3) - binary2(arr, item / 3) - 1L;
            long b = binary3(arr, item / 3 * 2) - binary2(arr, item / 3 * 2) - 1L;
            return (int) ((a * b) % 1000000007);
        }
    }

    private int binary2(int[] nums, int target) {
        if (nums[0] >= target) {
            return -1;
        }
        int st = 0;
        int end = nums.length - 1;
        while (st < end) {
            int m = st + ((end - st + 1) >> 1);
            if (nums[m] < target) {
                st = m;
            } else {
                end = m - 1;
            }
        }
        return st;
    }

    private int binary3(int[] nums, int target) {
        int end = nums.length - 1;
        if (nums[end] <= target) {
            return -1;
        }
        int st = 0;
        while (st < end) {
            int m = st + ((end - st) >> 1);
            if (nums[m] > target) {
                end = m;
            } else {
                st = m + 1;
            }
        }
        return st;
    }

}
